#include "maindrawingwidget.h"
#include <cassert>
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>

MainDrawingWidget::MainDrawingWidget(QWidget *parent) :
    QWidget(parent)
{
    this->setMouseTracking(true);
}

//Setup and connect LineShare object
void MainDrawingWidget::setLineShare(LineShare *lineshare){
    m_LineShare = lineshare;
    connect(m_LineShare, SIGNAL(repaint()), this, SLOT(repaint()));
}

//Clear LineShare stroke vecter and repaint drawing widget
void MainDrawingWidget::clear()
{
  m_LineShare->clear();
  this->repaint();
}

//Add points to common stoke vector
void MainDrawingWidget::mouseMoveEvent(QMouseEvent * e)
{
  if (e->buttons() & Qt::LeftButton)
  {
    m_LineShare->addPoint(e->pos());
    m_LineShare->setCurrentColor(this->m_Color);
    m_LineShare->setCurrentPenWidth(this->m_Width);
    this->repaint();
  }
}

//Add points to common stoke vector
void MainDrawingWidget::mousePressEvent(QMouseEvent * e)
{
  if (e->buttons() & Qt::LeftButton)
  {
      m_LineShare->addPoint(e->pos());
      m_LineShare->setCurrentColor(this->m_Color);
      m_LineShare->setCurrentPenWidth(this->m_Width);
  }
}

//Add points to common stoke vector
void MainDrawingWidget::mouseReleaseEvent(QMouseEvent * e)
{
    m_LineShare->addPoint(e->pos());
    m_LineShare->setCurrentColor(this->m_Color);
    m_LineShare->setCurrentPenWidth(this->m_Width);
    this->repaint();
    m_LineShare->strokeComplete();
}

//When repaint() is called repaint all strokes from the common stroke vector
void MainDrawingWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QPen pen = painter.pen();
    pen.setCapStyle(Qt::RoundCap);
    for (int i = 0; i < m_LineShare->m_commonStrokes.size(); i++){
        Stroke stroke = m_LineShare->m_commonStrokes.at(i);
        pen.setWidth(stroke.getPenWidth());
        pen.setColor(QColor(stroke.getR(), stroke.getG(), stroke.getB()));
        painter.setPen(pen);
        for(int j = 0; j<(stroke.m_points.size()-1); j++){
           painter.drawLine(stroke.m_points.at(j), stroke.m_points.at(j+1));
        }
    }
    Stroke stroke = m_LineShare->m_currentStroke;
    pen.setWidth(stroke.getPenWidth());
    pen.setColor(QColor(stroke.getR(), stroke.getG(), stroke.getB()));
    painter.setPen(pen);
    for(int j = 0; j<(stroke.m_points.size()-1); j++){
       painter.drawLine(stroke.m_points.at(j), stroke.m_points.at(j+1));
    }
}

//Update data members for pen settings
void MainDrawingWidget::penChanged(QColor color, int width)
{
    m_Color = color;
    m_Width = width;
}

